package chinawxd765.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override  
    public AuthenticationManager authenticationManagerBean() throws Exception {  
       return super.authenticationManagerBean();  
    }
	
	/**
	 * Request层面的配置
	 */
	@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
		
		logger.info("进入 WebSecurityConfig.configure(HttpSecurity http)...");
        httpSecurity
            .authorizeRequests()  // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/").permitAll()  // 不需要任何认证就可以访问
                .anyRequest().authenticated()  // 其他所有资源都需要认证，登陆后访问
                .and()
            .formLogin()  // 定义当需要用户登录时候，转到的登录页面
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
	            .logoutSuccessUrl("/login") //退出登录后的默认网址是”/home”
	            .permitAll()
	            .invalidateHttpSession(true)
                .and()
            .rememberMe()
            .tokenValiditySeconds(1209600);
    }
	
	@Override
    public void configure(WebSecurity web) throws Exception {
		
		logger.info("进入 WebSecurityConfig.configure(WebSecurity web)...");
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/**/favicon.ico");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    	
    	logger.info("进入 WebSecurityConfig.configureGlobal(AuthenticationManagerBuilder auth)...");
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");  // 在内存中创建了一个用户，该用户的名称为user，密码为password，用户角色为USER
	    
    }
	
}
